<?php
/**
 * Created by PhpStorm.
 * User: sen
 * Date: 16/7/21
 * Time: 下午2:05
 */
namespace app\models;

use Yii;
use yii\db\ActiveRecord;
class Category extends ActiveRecord
{

    public function getFirstCategoryList(){

        $categoryList = Category::find()->select(['category_id','category_name'])->where(['del_flag'=>1,'pid'=>-1])->asArray()->all();
        return $categoryList;
    }

    public function getSecondCategoryList($id){

        $categoryList = Category::find()->select(['category_id','category_name'])->where(['del_flag'=>1,'pid'=>$id])->asArray()->all();
        return $categoryList;
    }

    public function AddSecondCategory($id){

        $categoryList = Category::find()->select(['category_id','category_name'])->where(['del_flag'=>1,'pid'=>$id])->asArray()->all();
        return $categoryList;
    }


    //后台获取分类表单数据
    public function getTableData($limit,$offset,$search){

        $total = (new \yii\db\Query())
            ->from('hcps_category')
            ->where(['and',['del_flag' => 1],['>', 'pid', 0]])
            ->count();
        $query=new \yii\db\Query();
        if (!empty($search)) {
            $rows = $query->where(['and',['>', 'pid', 0],['like', 'category_name', $search],['del_flag' => 1]])->from('hcps_category')->orderBy('category_id DESC')->limit($limit)->offset($offset)->all();
        }else{
            $rows = $query->where(['and',['del_flag' => 1],['>', 'pid', 0]])->from('hcps_category')->orderBy('category_id DESC')->limit($limit)->offset($offset)->all();
        }
        for($i=0;$i<count($rows);$i++){
            $p_arr=Category::find()->select(['category_id','category_name'])->where(['category_id' => $rows[$i]['pid'],'pid'=>-1])->asArray()->all();
            $rows[$i]['p_category_id']=$p_arr[0]['category_id'];
            $rows[$i]['p_category_name']=$p_arr[0]['category_name'];
        }

        $rs=['total'=>$total,'rows'=>$rows];

        return $rs;

    }
    //通过一级分类的名字获取一级的分类id
    public function getCategoryId($category_name){
        $first_category = Category::find()->where(['category_name' => $category_name,'del_flag' => 1])->select('category_id')->scalar();
        return $first_category;
    }

}